package com.qf.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.qf.myexception.ServiceException;
import com.qf.pojo.UserPojo;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (token == null || token.trim().length() == 0)
            throw new ServiceException(800, "没有登录");
        String userIdStr = JWT.decode(token).getAudience().get(0);
        Integer userId = null;
        try {
            userId = Integer.valueOf(userIdStr);
        } catch (Exception e) {
            throw new ServiceException(800, "token不合法");
        }
        UserPojo user = (UserPojo) userService.queryOneUser(userId).getData();
        if (user==null)
            throw new ServiceException(800, "token不合法");
        JWTVerifier build = JWT.require(Algorithm.HMAC256(user.getUserPass())).build();
        try {
            build.verify(token);
        }catch (Exception e){
            throw new ServiceException(800, "token不合法");
        }
        return true;
    }
}
